package com.zzx.es;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzx.es.entity.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * @ClassName: com.zzx.es.ESTest_Client
 * @Description: ES文档创建测试类
 * @Author zhouzhixin
 * @Date 2021/8/13
 * @Version 1.0
 */
public class ESTest_Doc_Create {
    public static void main(String[] args) {
        // 建立可自动关闭的连接
        try (RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
        )) {
            // 插入数据
            IndexRequest request = new IndexRequest();
            request.index("user").id("1001");

            User user = new User("zs", "2", 18);
            ObjectMapper mapper = new ObjectMapper();
            String userJson = mapper.writeValueAsString(user);
            request.source(userJson, XContentType.JSON);
            // 发送请求
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            // 返回结果
            System.out.println(response.getResult());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
